package streamLogStaticJava.utils;

import org.apache.commons.lang3.StringUtils;
import streamLogStaticJava.utils.Exceptions.ExceptionCode;
import streamLogStaticJava.utils.Exceptions.ConsumerException;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

/**
 * @ClassName HbaseManagerUtil
 * @Description TODO
 * @Author dalong
 * @Date 2020/6/28 17:34
 * @Version 1.0
 **/

public class HbaseManagerUtil {


    private static ArrayList<String> atomlist = new ArrayList<>();
    private static ArrayList<String> keyPre;
    private static int keyPrelength;
    private static boolean isInit = false;


    /**生成62*62个原子前缀*/
    private static void init() {
        if(!isInit) {
            for (int i = '0'; i <= '9'; i++) {
                atomlist.add(String.valueOf((char) i));
            }
            for (int i = 'a'; i <= 'z'; i++) {
                atomlist.add(String.valueOf((char) i));
            }
            for (int i = 'A'; i <= 'Z'; i++) {
                atomlist.add(String.valueOf((char) i));
            }

            int length = atomlist.size();

            keyPre = new ArrayList<String>(length * length);
            for (int i = 0; i < length; i++) {
                for (int j = 0; j < length; j++) {
                    keyPre.add(atomlist.get(i) + atomlist.get(j));
                }
            }
            keyPrelength = length * length;

        }
    }


    /**自定义分区键 生成rowkey*/
    public static String getRowkey(String key){
        if(!isInit) init();
        if(!StringUtils.isEmpty(key)){
            return keyPre.get(key.hashCode() % keyPrelength)+"-"+key;
        }else {
            return "";
        }
    }


    /**
     * rowkey生成   ---使用各种jdk自带的加密算法实现
     * 1.保证前缀的分散
     * 2.保证同一个输入值的rowkey固定只有一个
     * 3.长度为16位
     * @param key
     * @param type  key的类型： number:纯数字，string:字符串
     * @return
     */
    public static String getRowkey(String key,String type) throws ConsumerException, UnsupportedEncodingException, NoSuchAlgorithmException {
        String rowkey = "";
        CodeStr codeStr = new CodeStr();
        if(StringUtils.isEmpty(type)){
            throw new ConsumerException(ExceptionCode.NULLPARAM.getValue());
        }
        switch (type){
            case "string":{
                rowkey = codeStr.EncoderStr(key,"MD5")+"-"+key;
                //rowkey = codeStr.EncoderStr(key,"MD5")+"-"+key;
                break;
            }
            /*默认number*/
            default:{
                rowkey = codeStr.EncoderStr(key,"HASH")+key;
            }
        }
        return rowkey;
    }


    public static void main(String[] args) {
        System.out.println(getRowkey("1234"));
    }

}
